package com.javafxboot.util;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.javafxboot.entity.PrintUrl;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.PrintService;
import java.awt.print.*;
import java.io.*;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Tw711 {
    public static void readPdf(PrintUrl data) throws Exception{
        // 创建webclient
        WebClient webClient = new WebClient();
        // 取消 JS 支持
        webClient.getOptions().setJavaScriptEnabled(false);
        // 取消 CSS 支持
        webClient.getOptions().setCssEnabled(false);
        // 获取指定网页实体
//        try {
            HtmlPage page = (HtmlPage) webClient.getPage(data.getUrl());


            final HtmlForm form = page.getForms().get(0);
            String tempvar = form.getInputByName("tempvar").getDefaultValue();
            String deadlinedate = form.getInputByName("deadlinedate").getDefaultValue();
            String trade_describe = form.getInputByName("trade_describe").getDefaultValue();
            String service_type = form.getInputByName("service_type").getDefaultValue();
            String sender_phone = form.getInputByName("sender_phone").getDefaultValue();
            String receiver_phone = form.getInputByName("receiver_phone").getDefaultValue();
            String eshopid = form.getInputByName("eshopid").getDefaultValue();
            String eshopsonid = form.getInputByName("eshopsonid").getDefaultValue();
            String paymentno = form.getInputByName("paymentno").getDefaultValue();
            String deadlinetime = form.getInputByName("deadlinetime").getDefaultValue();
            String show_type = form.getInputByName("show_type").getDefaultValue();
            String daishou_account = form.getInputByName("daishou_account").getDefaultValue();
            String online_url = form.getInputByName("online_url").getDefaultValue();
            String trade_no = form.getInputByName("trade_no").getDefaultValue();
            String account = form.getInputByName("account").getDefaultValue();
            String sender = form.getInputByName("sender").getDefaultValue();
            String url = form.getInputByName("url").getDefaultValue();
            String trade_description = form.getInputByName("trade_description").getDefaultValue();
            String return_storeid = form.getInputByName("return_storeid").getDefaultValue();
            String payment_cpname = form.getInputByName("payment_cpname").getDefaultValue();
            String receiver = form.getInputByName("receiver").getDefaultValue();
            String validationno = form.getInputByName("validationno").getDefaultValue();
            String orderno = form.getInputByName("orderno").getDefaultValue();
            String receiver_storeid = form.getInputByName("receiver_storeid").getDefaultValue();

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("tempvar="+tempvar+"&");
            stringBuilder.append("deadlinedate="+deadlinedate+"&");
            stringBuilder.append("trade_describe="+trade_describe+"&");
            stringBuilder.append("service_type="+service_type+"&");
            stringBuilder.append("sender_phone="+sender_phone+"&");
            stringBuilder.append("receiver_phone="+receiver_phone+"&");
            stringBuilder.append("eshopid="+eshopid+"&");
            stringBuilder.append("eshopsonid="+eshopsonid+"&");
            stringBuilder.append("paymentno="+paymentno+"&");
            stringBuilder.append("deadlinetime="+deadlinetime+"&");
            stringBuilder.append("show_type="+show_type+"&");
            stringBuilder.append("daishou_account="+daishou_account+"&");
            stringBuilder.append("online_url="+online_url+"&");
            stringBuilder.append("trade_no="+trade_no+"&");
            stringBuilder.append("account="+account+"&");
            stringBuilder.append("sender="+sender+"&");
            stringBuilder.append("url="+url+"&");
            stringBuilder.append("trade_description="+trade_description+"&");
            stringBuilder.append("return_storeid="+return_storeid+"&");
            stringBuilder.append("payment_cpname="+payment_cpname+"&");
            stringBuilder.append("receiver="+receiver+"&");
            stringBuilder.append("validationno="+validationno+"&");
            stringBuilder.append("orderno="+orderno+"&");
            stringBuilder.append("receiver_storeid="+receiver_storeid);


            String returnString = HttpClientUtil.sendHttpPostText("https://epayment.7-11.com.tw/C2C/C2CWeb/GetPinNo.aspx", stringBuilder.toString());
            //System.out.println(returnString);
            String formDataString= "PinCodeNumber="+returnString;
            //map.put("PinCodeNumber", returnString);

            String re = HttpClientUtil.sendHttpPost711("https://epayment.7-11.com.tw/C2C/C2CWeb/PrintC2CPinCode.aspx", formDataString);


            re = re.replace("BarCode.ashx?CodeValue", "https://epayment.7-11.com.tw/C2C/C2CWeb/BarCode.ashx?CodeValue");
            re = re.replace("QRCode.ashx?CodeValue", "https://epayment.7-11.com.tw/C2C/C2CWeb/QRCode.ashx?CodeValue");
            re = re.replace("id=\"lblRecvshop1\"", "style=\"FONT-SIZE: 32px\" id=\"lblRecvshop1\"");
            re = re.replace("id=\"lblRecver1\"", " style=\"font-size:26px;\" id=\"lblRecver1\"");
            re = re.replace("style=\"margin: 0;", " style=\"margin: 0;height:130mm; width:85mm;");


            Date dNow = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");
            ft.format(dNow);

            isexitsPath(""+ft.format(dNow)+"\\pdf");

            OutputStreamWriter pw = null;//定义一个流
            pw = new OutputStreamWriter(new FileOutputStream(ft.format(dNow)+""+data.getOrderSn()+".html"),"UTF-8");//确认流的输出文件和编码格式，此过程创建了“test.txt”实例
            pw.write(re);
            pw.close();//关闭流
            //-s A7
            File directory = new File("");//参数为空
            String courseFile = directory.getCanonicalPath() ;
            System.out.println(courseFile);
            cmd(directory+"wkhtmltopdf\\bin\\wkhtmltopdf.exe -L 5 -R 0 -T 5 -B 0  --page-height 150 --page-width 100 --zoom 1.2 "+courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+".html "+courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+".pdf");

            if(data.getIsPrint()){
                defaultPrintPDF(courseFile+"\\"+ft.format(dNow)+data.getOrderSn()+".pdf");
            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static boolean isexitsPath(String path)throws InterruptedException{
        String [] paths=path.split("\\\\");
        StringBuffer fullPath=new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file=new File(fullPath.toString());
            if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
                if(!file.exists()){
                    file.mkdir();
                    System.out.println("创建目录为："+fullPath.toString());
                }
            }
        }
        File file=new File(fullPath.toString());//目录全路径
        if (!file.exists()) {
            return true;
        }else{
            return false;
        }
    }

    public static void defaultPrintPDF(String pdfPath) throws IOException, PrinterException {

        File file = new File(pdfPath);
        // 读取pdf文件
        PDDocument document = PDDocument.load(file);
        // 创建打印任务
        PrinterJob job = PrinterJob.getPrinterJob();

        job.setPageable(new PDFPageable(document));

        Paper paper = new Paper();
        // 设置打印纸张大小
        paper.setSize(283,425); // 1/72 inch
        // 设置打印位置 坐标
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        // override the page format
        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.SCALE_TO_FIT), pageFormat, 1);
        job.setPageable(book);
        // 开始打印
        job.print();

    }


    public static boolean cmd(String command) throws Exception{
        boolean flag = false;
        String line = null;
        StringBuilder sb = new StringBuilder();
        Runtime runtime = Runtime.getRuntime();
//        try {
            Process process = runtime.exec(command);
            BufferedReader	bufferedReader = new BufferedReader
                    (new InputStreamReader(process.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {

            }
            flag = true;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return flag;
    }




}
